import axios from "axios";
import { ref } from "vue";
import { HWMI_URLS } from "../../modules/Api";

export default function ({ emit }, { successEvent, errorEvent }) {
    const batchMode = ref("ADD_ENTITY");
    const isBatchUploadLoadingShow = ref(false);

    const onSelectBatchFileClick = () => {
        document.getElementById("in-batch-file").click();
    };

    const onBatchFileChange = e => {
        if (e.target.files.length === 0) {
            return;
        }

        isBatchUploadLoadingShow.value = true;

        const fileReader = new FileReader();
        fileReader.readAsText(e.target.files[0]);
        fileReader.onload = res => {
            axios.post(HWMI_URLS.managementUrls.graphDbManagementUrls.batchUploadUrl, {
                mode:batchMode.value,
                text: res.target.result
            })
                .then(res1 => {
                    if (res1.data.success) {
                        emit(successEvent, "操作成功");
                    }
                    else {
                        emit(errorEvent, res1.data.message);
                    }
                })
                .catch(reason => {
                    console.log(reason);
                    emit(errorEvent, reason);
                })
                .finally(() => {
                    isBatchUploadLoadingShow.value = false;
                });
            // clear file value to ensure onchange will be triggered again
            // if we load the same file next time.
            document.getElementById("in-batch-file").value = "";
        }
    };

    return {
        batchMode,
        isBatchUploadLoadingShow,
        onSelectBatchFileClick,
        onBatchFileChange
    };
}